<template>
  <div class="goal-setting-page">
    <!-- 当前目标卡片 -->
    <el-card class="current-goal" v-loading="loading">
      <template #header>
        <div class="card-header">
          <h2>当前目标</h2>
          <el-button type="primary" @click="showAddDialog">设置新目标</el-button>
        </div>
      </template>
      
      <el-empty v-if="!currentGoal" description="暂无进行中的目标">
        <el-button type="primary" @click="showAddDialog">设置目标</el-button>
      </el-empty>
      
      <div v-else class="goal-info">
        <div class="info-item">
          <span class="label">目标类型：</span>
          <span class="value">{{ currentGoal.goalType }}</span>
        </div>
        <div class="info-item">
          <span class="label">目标体重：</span>
          <span class="value">{{ currentGoal.targetWeight }}kg</span>
        </div>
        <div class="info-item">
          <span class="label">每日卡路里目标：</span>
          <span class="value">{{ currentGoal.dailyCalorieTarget }}千卡</span>
        </div>
        <div class="info-item">
          <span class="label">目标周期：</span>
          <span class="value">{{ formatDate(currentGoal.startDate) }} 至 {{ formatDate(currentGoal.endDate) }}</span>
        </div>
        <div class="actions">
          <el-button type="warning" @click="handleEdit(currentGoal)">编辑</el-button>
        </div>
      </div>
    </el-card>

    <!-- 历史目标列表 -->
    <el-card class="goal-history">
      <template #header>
        <h2>目标历史</h2>
      </template>
      
      <el-table :data="historyGoals" v-loading="loading">
        <el-table-column prop="goalType" label="目标类型" />
        <el-table-column prop="targetWeight" label="目标体重(kg)" />
        <el-table-column prop="dailyCalorieTarget" label="每日卡路里目标" />
        <el-table-column label="目标周期" min-width="200">
          <template #default="{ row }">
            {{ formatDate(row.startDate) }} 至 {{ formatDate(row.endDate) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getGoalStatus(row).type">
              {{ getGoalStatus(row).text }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑目标对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingGoal ? '编辑目标' : '设置新目标'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="goalForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="目标类型" prop="goalType">
          <el-select v-model="goalForm.goalType" placeholder="请选择目标类型">
            <el-option label="减重" value="减肥" />
            <el-option label="增肌" value="增肌" />
            <el-option label="维持健康" value="保持健康" />
          </el-select>
        </el-form-item>

        <el-form-item label="目标体重(kg)" prop="targetWeight">
          <el-input-number 
            v-model="goalForm.targetWeight"
            :precision="1"
            :step="0.1"
            :min="30"
            :max="200"
          />
        </el-form-item>

        <el-form-item label="每日卡路里目标" prop="dailyCalorieTarget">
          <el-input-number 
            v-model="goalForm.dailyCalorieTarget"
            :step="100"
            :min="1000"
            :max="5000"
          />
          <span class="unit">千卡</span>
        </el-form-item>

        <el-form-item label="目标周期" required>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled-date="disabledDate"
            @change="handleDateChange"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import { getAllGoals, getCurrentGoal, addGoal, updateGoal } from '@/api/goals'

const store = useStore()
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const formRef = ref(null)
const dateRange = ref(null)
const userId = localStorage.getItem('userId')
const editingGoal = ref(null)
const goals = ref([])

// 计算当前目标和历史目标
const currentGoal = computed(() => store.state.user.currentGoal)
const historyGoals = computed(() => {
  return goals.value.filter(goal => goal.goalId !== currentGoal.value?.goalId)
})

// 表单数据
const goalForm = ref({
  goalType: '',
  targetWeight: null,
  dailyCalorieTarget: 2000,
  startDate: '',
  endDate: ''
})

// 表单验证规则
const rules = {
  goalType: [{ required: true, message: '请选择目标类型', trigger: 'change' }],
  targetWeight: [{ required: true, message: '请输入目标体重', trigger: 'blur' }],
  dailyCalorieTarget: [{ required: true, message: '请输入每日卡路里目标', trigger: 'blur' }]
}

// 获取所有目标
const fetchGoals = async () => {
  loading.value = true
  try {
    const [currentRes, allRes] = await Promise.all([
      getCurrentGoal(userId),
      getAllGoals(userId)
    ])
    
    if (currentRes?.success) {
      store.dispatch('user/setCurrentGoal', currentRes.data)
    }
    
    if (allRes?.success) {
      goals.value = allRes.data || []
    }
  } catch (error) {
    console.error('获取目标失败:', error)
    ElMessage.error('获取目标失败')
  } finally {
    loading.value = false
  }
}

// 显示添加对话框
const showAddDialog = () => {
  editingGoal.value = null
  resetForm()
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (goal) => {
  editingGoal.value = goal
  goalForm.value = { ...goal }
  dateRange.value = [new Date(goal.startDate), new Date(goal.endDate)]
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (!dateRange.value) {
      ElMessage.warning('请选择目标周期')
      return
    }
    
    submitting.value = true
    const goalData = {
      dailyCalorieTarget: goalForm.value.dailyCalorieTarget,
      endDate: goalForm.value.endDate,
      goalType: goalForm.value.goalType,
      startDate: goalForm.value.startDate,
      targetWeight: goalForm.value.targetWeight
    }
    
    let response
    if (editingGoal.value) {
      response = await updateGoal(userId, editingGoal.value.goalId, goalData)
    } else {
      response = await addGoal(userId, goalData)
    }
    
    if (response?.success) {
      ElMessage.success(editingGoal.value ? '更新目标成功' : '设置目标成功')
      dialogVisible.value = false
      await fetchGoals()
    } else {
      throw new Error(response?.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  dateRange.value = null
  goalForm.value = {
    goalType: '',
    targetWeight: null,
    dailyCalorieTarget: 2000,
    startDate: '',
    endDate: ''
  }
}

// 日期相关函数
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

const handleDateChange = (val) => {
  if (val) {
    goalForm.value.startDate = formatDate(val[0])
    goalForm.value.endDate = formatDate(val[1])
  } else {
    goalForm.value.startDate = ''
    goalForm.value.endDate = ''
  }
}

const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

// 获取目标状态
const getGoalStatus = (goal) => {
  const now = new Date()
  const startDate = new Date(goal.startDate)
  const endDate = new Date(goal.endDate)
  
  if (now < startDate) {
    return { type: 'info', text: '未开始' }
  } else if (now > endDate) {
    return { type: 'danger', text: '已结束' }
  } else {
    return { type: 'success', text: '进行中' }
  }
}

onMounted(() => {
  fetchGoals()
})
</script>

<style lang="scss" scoped>
.goal-setting-page {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h2 {
      margin: 0;
      font-size: 18px;
    }
  }
  
  .goal-info {
    .info-item {
      margin-bottom: 12px;
      
      .label {
        color: var(--el-text-color-secondary);
        margin-right: 8px;
      }
      
      .value {
        font-weight: 500;
      }
    }
    
    .actions {
      margin-top: 16px;
      display: flex;
      justify-content: flex-end;
    }
  }
  
  .unit {
    margin-left: 8px;
    color: var(--el-text-color-secondary);
  }
}

@media (max-width: 768px) {
  .goal-setting-page {
    padding: 10px;
  }
}
</style> 